import { Ellipsis } from '@/components/Ellipsis';
import { getDrawingInfoPreviewUrl } from '@/services/design/drawingReview';
import {
  addMutiDrawingReview,
  delProductDrawingInfo,
  downloadProductDrawingInfo,
  getDrawingTypeList,
  getProductDrawingInfoByPage,
  uploadDrawing,
} from '@/services/design/productDrawingInfo';
import { tableSearchPublicConfig } from '@/utils/filterUtils';
import { filterTranNew, sortTran } from '@/utils/requestUtil';
import { ArrowLeftOutlined, UploadOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Alert, Button, Form, Input, message, Modal, Select, Upload } from 'antd';
import React, { useRef, useState } from 'react';
import { history } from 'umi';
const ProductNosubmittedDrawingInfo: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [optionsstandfile, setoptionsstandfile] = useState([]);
  const [file, setFile] = useState();
  const [fileList, setFileList] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]); //图纸变更列表选择选项
  //   const [changeStatusColor, setChangeStatusColor] = useState('status-color-white base-status');
  const [form] = Form.useForm();
  const ref = useRef(null);
  const [scrollY, setScrollY] = useState('');
  /**
   * @description: 图纸上传变更状态，绿色为新增，黄色为变更，白色为原始
   * @param {any} text
   * @return {*}
   */
  const changeStatusColor = (text: any) => {
    if (text === '1') {
      return <div className="status-color-green base-status"></div>;
    } else if (text === '2') {
      return <div className="status-color-yellow base-status"></div>;
    } else {
      return <div className="status-color-white base-status"></div>;
    }
  };
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '图纸编号',
      dataIndex: 'drawingCode',
      width: 180,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '图纸名称',
      dataIndex: 'drawingName',
      width: 320,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    // {
    //   title: '审核状态',
    //   dataIndex: 'changeStatus',
    //   align: 'center',
    //   sorter: true,
    //   render: (text, record, _, action) => (
    //     <span>{text === 0 ? '待审核' : text === 2 ? '通过' : '驳回'}</span>
    //   ),
    // },
    {
      title: '变更状态',
      dataIndex: 'changeOrAdd',
      align: 'center',
      sorter: true,
      render: (text, record, _, action) => changeStatusColor(text),
    },

    {
      title: '文件类别',
      dataIndex: 'category',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      valueType: 'select',
      request: async () => {
        const gettype = await getDrawingTypeList(null);
        const productfiletype: any[] = [];
        gettype.data.map((item: any, index: any) => {
          productfiletype.push({ value: item, label: item });
        });
        return productfiletype;
      },
    },
    {
      title: '产品/柜体编号',
      dataIndex: 'productCode',
      width: 220,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      search: false,
    },
    {
      title: '版本号',
      dataIndex: 'version',
      width: 100,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis('v' + text)}</>,
    },
    {
      title: '启用状态',
      dataIndex: 'isActive',
      width: 100,
      align: 'center',
      sorter: true,
      render: (text, record, _, action) => {
        return <div>{record.isActive == 1 ? '是' : '否'}</div>;
      },
      valueType: 'select',
      request: async () => [
        { label: '是', value: 1 },
        { label: '否', value: 0 },
      ],
    },
    {
      title: '图纸打印标识',
      dataIndex: 'printFlag',
      width: 135,
      align: 'center',
      sorter: true,
      render: (text, record, _, action) => {
        return <div>{record.printFlag == 1 ? '已打印' : '未打印'}</div>;
      },
      search: false,
    },
    {
      title: '归档标识',
      dataIndex: 'archiveFlag',
      width: 120,
      align: 'center',
      sorter: true,
      render: (text, record, _, action) => {
        return <div>{record.archiveFlag == 1 ? '已归档' : '未归档'}</div>;
      },
      search: false,
    },
    {
      title: '柜体图纸描述',
      dataIndex: 'drawingSpec',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      width: 220,
      render: (text, record, _, action) => [
        <a
          key="viewKey"
          onClick={async () => {
            if (record.drawingName == null) {
              message.warning('该文件不能预览');
            } else {
              const filetype = record.drawingName.split('.').pop();
              if (filetype == 'pdf' || filetype == 'png' || filetype == 'jpg') {
                const drawingUrl = await getDrawingInfoPreviewUrl({ drawingId: record.id });
                const w = window.open(record.drawingName);
                w.location.href = drawingUrl.message;
              } else {
                message.warning('该文件不能预览');
              }
            }
          }}
        >
          预览
        </a>,
        <a
          key="downloadKey"
          onClick={() => {
            downloadProductDrawingInfo({ id: record.id }).then((res) => {
              console.log(res);
              const aLink = document.createElement('a');
              document.body.appendChild(aLink);
              aLink.style.display = 'none';
              aLink.href = window.URL.createObjectURL(res);
              aLink.setAttribute('download', `${record.drawingName}`);
              aLink.click();
              document.body.removeChild(aLink);
            });
          }}
        >
          下载
        </a>,
        <a
          key="deleteKey"
          // disabled={history.location.state.reviewState == '2'}
          disabled={record.changeOrAdd === '0'} //当为原始图纸，则不可以删除，如果为新增和变更图纸，则可以删除
          onClick={() => {
            if (record.changeOrAdd === '0') {
              //变更状态为变更和原始
              message.warning('原始图纸不允许删除！');
            } else {
              Modal.confirm({
                title: '删除',
                content: '确定要删除吗',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                  await delProductDrawingInfo({ id: record.id });
                  actionRef.current?.reload();
                  message.success('删除成功!');
                },
              });
            }
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const handleSelect = (record, selected) => {
    if (record.changeStatus === 'status-color-white base-status') {
      // 如果变更状态为白色，则不允许选择
      return;
    }

    if (selected) {
      // 选中行
      setSelectedRowKeys((keys) => [...keys, record.key]);
    } else {
      // 取消选中行
      setSelectedRowKeys((keys) => keys.filter((key) => key !== record.key));
    }
  };
  /**
   * @description: 图纸变更选择图纸列表事件
   * @return {*}
   */
  // const rowSelection = {
  //   selectedRowKeys,
  //   onChange: (selectedRowKeys, selectedRows) => {
  //     setSelectedRowKeys(selectedRowKeys);
  //     setSelectedRows(selectedRows);
  //     console.log(selectedRowKeys, selectedRows);
  //   },
  //   onSelect: handleSelect, // 调用 handleSelect 函数
  // };
  // 选中项目，导出工时模板
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: string[]) => {
      const temp = [];
      if (selectedRows !== null) {
        selectedRows.map((item) => {
          temp.push(item);
        });
      }
      setSelectedRows(temp); //保存项目信息
    },
    getCheckboxProps: (record) => {
      if (record.changeOrAdd === '0') {
        return { disabled: true };
      } else {
        return null;
      }
    },
  };
  const getproductInfo = async () => {
    // 获取图纸类型
    const gettype = await getDrawingTypeList(null);
    const productfiletype: any[] = [];
    gettype.data.map((item: any, index: any) => {
      if (item == '电气原理图' || item == '箱柜接线表') {
        productfiletype.push({ value: item, label: item + ' *' });
      } else {
        productfiletype.push({ value: item, label: item });
      }
    });
    setoptionsstandfile(productfiletype);
  };
  /**
   * @description:图纸变更上传
   * @return {null}
   */
  const handleSubmit = async () => {
    setConfirmLoading(true);
    form
      .validateFields()
      .then(async () => {
        //获取表单数据
        const productCode = history.location.state.productCode;
        const formData = new window.FormData();
        //多文件
        fileList?.map((item: any) => {
          formData.append('file', item.originFileObj); //需要将file类型的文件转入formData中，不然后端接收不到
        });
        const res = { ...form.getFieldsValue(), productCode: productCode, file: formData };
        // res.drawingId = res.id;
        console.log(res);
        const { drawingNumber, drawingName, category } = history.location.state;
        const result = await uploadDrawing(res);
        console.log('图纸审批上传结果：', result);
        if (result != null) {
          message.success('上传成功');
          form.resetFields();
        }
        setConfirmLoading(false);
        form.resetFields();
        setFileList([]);
        setModalVisit(false);
        actionRef.current!.reload();
      })
      .catch(() => {
        setConfirmLoading(false);
      });
  };

  const handleSubmit2 = async (type: any) => {
    try {
      if (type === '提交审核') {
        if (selectedRows.length === 0) {
          message.error('请选择要审批的图纸！');
        } else {
          const newSelectedRows = [];
          selectedRows.map((item: any, index: any) => {
            if (item.changeStatus === 2) {
              message.error('原始图纸不可以被提交，只允许提交新建和变更图纸');
              throw new Error('原始图纸不可以被提交！');
            }
            newSelectedRows.push({ ...item, drawingId: item.id });
          });
          console.log('待审批图纸:', newSelectedRows);
          const result = await addMutiDrawingReview(newSelectedRows);
          console.log(result);
          if (result) {
            message.success('提交成功');
            actionRef.current!.reload();
          }
        }
      }
      if (formTitle == '上传图纸') {
        form
          .validateFields()
          .then(async () => {
            const res = {
              ...form.getFieldsValue(),
              productCode: history.location.state.productCode,
            };
            const formData = new window.FormData();
            formData.append('file', file);
            res.file = formData;
            res.drawingId = res.id;
            console.log(res);
            console.log(formData.get('file'));
            const result = await uploadDrawing(res);
            if (result != null) {
              message.success('上传成功');
              form.resetFields();
            }
            setConfirmLoading(false);
            setModalVisit(false);
            actionRef.current.reload();
          })
          .catch(() => {
            setConfirmLoading(false);
          });
      } else if (formTitle == '编辑') {
        form
          .validateFields()
          .then(async () => {
            const res = {
              ...form.getFieldsValue(),
              productCode: history.location.state.productCode,
            };
            const formData = new window.FormData();
            formData.append('file', file);
            res.file = formData;
            res.drawingId = res.id;
            console.log(res);
            console.log(formData.get('file'));
            const result = await updateProductDrawingInfo2(res);
            if (result != null) {
              message.success('修改成功');
              form.resetFields();
            }
            setConfirmLoading(false);
            setModalVisit(false);
            actionRef.current.reload();
          })
          .catch(() => {
            setConfirmLoading(false);
          });
        // const res = { ...form.getFieldsValue(), productCode: history.location.state.productCode };
        // const formData = new window.FormData();
        // formData.append('file', file);
        // res.file = formData;
        // res.drawingId = res.id;
        // console.log(res);
        // console.log(formData.get('file'));
        // const result = await updateProductDrawingInfo2(res);
        // if (result != null) {
        //   message.success('修改成功');
        //   form.resetFields();
        // }
      }
    } catch (error) {
      console.log(error?.message);
    }
  };

  const onFilesChange = (info: any) => {
    setFileList(info.fileList);
  };
  // const onFilesChange = (info: any) => {
  //   // console.log(info.file.status,'info.file.status');
  //   // if (info.file.status === 'uploading') {
  //   //   setLoading(true);
  //   //   return;
  //   // }
  //   // if (info.file.status === 'done') {
  //   //   setLoading(false);
  //   //   setFileList(info.fileList);
  //   //   return;
  //   // }
  //   const isLt = info.size / 1024 / 1024  < 5;
  //   if (isLt) {
  //     setFileList(info.fileList);
  //     console.log('保存file');
  //   }
  // };

  /* 在文件上传之前进行检验 */
  const handleBeforeUpload = (info: any) => {
    //检验文件大小
    // info.size文件大小单位是字节
    const isLt = info.size / 1024 / 1024 < 5;
    if (!isLt) {
      alert(`上传文件大小不能超过 ${5} MB!`);
    }
    // return isLt || Upload.LIST_IGNORE; //这里必须要返回false，来阻止原生的组件的默认action行为，不然会显示存储错误的信息
    return false;
  };

  // const beforeUpload = (file) => {
  //   setFile(file);
  //   return false;
  // };

  return (
    <>
      <ProTable
        headerTitle="技术文件查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={tableSearchPublicConfig}
        toolBarRender={(action, { selectedRows }) => [
          <div className="projectScheduleGroup" hidden={history.location.state.reviewState == 0}>
            <span>原始：</span>
            <img src="../wks.gif" />
            <span>新增：</span>
            <img src="../zxz.gif" />
            <span>变更：</span>
            <img src="../zt.gif" />
          </div>,
          <Button
            key="button"
            icon={<ArrowLeftOutlined />}
            onClick={() => {
              history.push({
                pathname: '/design/productDesign',
                query: {
                  tab_state: history.location.state.reviewState, //传参
                },
              });
            }}
            type="primary"
          >
            返回
          </Button>,
          <Button
            key="button"
            hidden={history.location.state.reviewState == 1}
            icon={<UploadOutlined />}
            onClick={() => {
              setCreateOrUpdate(true);
              setFormTitle('上传图纸');
              setModalVisit(true);
              // form.setFieldsValue({
              //   category: optionsstandfile[0].value,
              // });
            }}
            type="primary"
          >
            上传图纸
          </Button>,
          <Button
            hidden={history.location.state.reviewState == 0}
            key="submit"
            type="primary"
            onClick={() => {
              setFormTitle('提交审核');
              handleSubmit2('提交审核'); //异步调用递交函数，等待useStata异步更改完数据
            }}
          >
            提交审批
          </Button>, //todo
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     const filter_ref = { productCode: history.location.state.productCode };
          //     const filters = filterTranNew(filter_ref);
          //     exportProductDrawingInfo({
          //       current: 1,
          //       pageSize: 150000,
          //       filters: filters,
          //     }).then((res) => {
          //       const aLink = document.createElement('a');
          //       document.body.appendChild(aLink);
          //       aLink.style.display = 'none';
          //       aLink.href = window.URL.createObjectURL(res);

          //       aLink.setAttribute(
          //         'download',
          //         `ProductDrawingInfo_${new Date()}_${new Date()}.xlsx`,
          //       );
          //       aLink.click();
          //       document.body.removeChild(aLink);
          //     });
          //   }}
          //   type="primary"
          // >
          //   导出
          // </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const res = { ...params, productCode: history.location.state.productCode };
          const sorters = sortTran(sort);
          const filters = filterTranNew(res);
          //增加一个过滤条件
          filters.push({
            "andOr": 'and',
            "field": 'changeStatus',
            "operator": 'in',
            "value": [0, 2],
          })
          const result = await getProductDrawingInfoByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          getproductInfo();
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={
          history.location.state.reviewState == 0
            ? columns.filter(function (item) {
              return item.dataIndex != 'changeStatus';
            })
            : columns
        }
        scroll={{ x: 2000, y: 350 }}
        // scroll={{ x: 2000, y: 400 }}
        rowSelection={{ selectedRows, ...rowSelection }}
      // 选中项目，导出工时模板
      //   const rowSelection = {
      //     onChange: (selectedRowKeys: React.Key[], selectedRows: string[]) => {
      //       const temp = [];
      //       if (selectedRows !== null) {
      //         selectedRows.map((item) => {
      //           temp.push(item);
      //         });
      //       }
      //       setSelections(temp); //保存项目信息
      //     },
      //   };
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => {
          form.resetFields();
          setModalVisit(false);
        }}
      >
        <Alert
          description="上传的图纸中,图纸名称和文件类别与现有图纸一样,则为变更,其余情况为新增"
          type="warning"
          showIcon
          style={{ marginBottom: 20 }}
        />
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          {/* <Form.Item
            label="图纸编号" // 新增图纸编号
            name="drawingNumber" // 表单字段名称为 drawingNumber
            rules={[{ required: true, message: '请输入图纸编号!' }]} // 添加必填规则
          >
            <Input />
          </Form.Item> */}
          <Form.Item
            label="文件类别"
            name="category"
            rules={[{ required: true, message: '请选择文件类别!' }]}
          >
            <Select
              placeholder="请选择文件类别"
              defaultValue=""
              onChange={() => { }}
              options={optionsstandfile}
            />
          </Form.Item>
          <Form.Item
            label="图纸上传"
            name="file"
            rules={[{ required: true, message: '请上传图纸附件!' }]}
          >
            <Upload
              // fileList={fileList}
              onChange={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={handleBeforeUpload}
              multiple
              maxCount={history.location.state.reviewState == 2 ? 1 : 999}
            >
              <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>
          </Form.Item>
          <Form.Item label="图纸描述" name="drawingSpec">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};
export default ProductNosubmittedDrawingInfo;
